package com.ywjh.inter.servlet;

import com.ywjh.inter.common.ApiConsts;
import com.ywjh.inter.common.SystemConfig;
import com.ywjh.inter.entity.SrcDataValue;
import com.ywjh.inter.service.BioLandService;
import com.ywjh.inter.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

public class Blood4G extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = -612408149688351559L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        String data = req.getParameter("data");
        if(data!=null && !"".equals(data)){
            System.out.println("接收到血糖数据："+data);
            //SrcDataValue srcDatavalue = new SrcDataValue(data);
            //BioLandService.getInstance().blglu4G(srcDatavalue);
            // 给血糖设备回复报文
            StringBuilder rslt = new StringBuilder("+IP");
            rslt.append(getServerIp(req));
            rslt.append(getServerDate());
            rslt.append("OK");
            byte[] towrite = rslt.toString().getBytes();
            resp.setContentLength(towrite.length);
            //OutputStream outWriter = resp.getOutputStream();
            PrintWriter pw = resp.getWriter();
            pw.print(rslt.toString());
            pw.close();
        }
        // 校验数据合法性
        /*if (BioLandService.getInstance().checkReceivedData(data)) {
            SrcDataValue srcDatavalue = new SrcDataValue(data);
            // 只接收血糖、血压数据!!!!!!!!!!!!!!!!
            if (!(ApiConsts.DataTypeEnum.BLPRESSURE.getCode().equals(srcDatavalue.getDeviceType())
                    || ApiConsts.DataTypeEnum.BLGLUCOSE.getCode().equals(srcDatavalue.getDeviceType()))) {
                return;
            }
            boolean isSuccess = false;
            // 处理上报的数据
            if (ApiConsts.DataTypeEnum.BLGLUCOSE.getCode().equals(srcDatavalue.getDeviceType())) {
                isSuccess = BioLandService.getInstance().blglu(srcDatavalue);
            } else if (ApiConsts.DataTypeEnum.BLPRESSURE.getCode().equals(srcDatavalue.getDeviceType())) {
                isSuccess = BioLandService.getInstance().bpress(srcDatavalue);
            }
            System.out.println("receiced data=" + data + " isSuccess=" + isSuccess + " srcDatavalue==" + srcDatavalue);
            // 给血糖设备回复报文
            if (true) {
                StringBuilder rslt = new StringBuilder("+IP");
                rslt.append(getServerIp(req));
                rslt.append(getServerDate());
                rslt.append("OK");
                byte[] towrite = rslt.toString().getBytes();
                resp.setContentLength(towrite.length);
                //OutputStream outWriter = resp.getOutputStream();
                PrintWriter pw = resp.getWriter();
                pw.print(rslt.toString());
                pw.close();
            }
        }*/
    }

    /**
     * 获取请求端ip地址
     *
     * @param request
     * @return
     */
    private String getServerIp(HttpServletRequest request) {

        String[] ips = StringUtil.toString(SystemConfig.DOMAIN).split("\\.");

        if ((null == ips) || (0 >= ips.length)) {
            return "";
        }

        String ports = StringUtils.leftPad(Integer.toHexString(request.getLocalPort()), 4, "0");

        StringBuilder ipsb = new StringBuilder();

        int sum = 0;

        for (int i = 0; i < ips.length; i++) {
            ipsb.append(StringUtils.leftPad(Integer.toHexString(Integer.valueOf(ips[i]).intValue()), 2, "0"));
            sum ^= Integer.valueOf(ips[i]).intValue();
        }

        sum ^= Integer.valueOf(ports.substring(2, 4), 16).intValue();
        ipsb.append(ports.substring(2, 4));
        sum ^= Integer.valueOf(ports.substring(0, 2), 16).intValue();
        ipsb.append(ports.substring(0, 2));
        ipsb.append(Integer.toHexString(sum));

        return ipsb.toString().toUpperCase();
    }

    /**
     * 获取服务器时间
     *
     * @return
     */
    private String getServerDate() {

        StringBuilder datasb = new StringBuilder();

        int sum = 0;

        Calendar cal = Calendar.getInstance();
        Integer year = Integer.valueOf(cal.get(1) % 100);
        datasb.append(StringUtils.leftPad(Integer.toHexString(year.intValue()), 2, "0"));
        sum ^= year.intValue();

        Integer month = Integer.valueOf(cal.get(2) + 1);
        datasb.append(StringUtils.leftPad(Integer.toHexString(month.intValue()), 2, "0"));
        sum ^= month.intValue();

        Integer day = Integer.valueOf(cal.get(5));
        datasb.append(StringUtils.leftPad(Integer.toHexString(day.intValue()), 2, "0"));
        sum ^= day.intValue();

        Integer hour = Integer.valueOf(cal.get(11));
        datasb.append(StringUtils.leftPad(Integer.toHexString(hour.intValue()), 2, "0"));
        sum ^= hour.intValue();

        Integer minute = Integer.valueOf(cal.get(12));
        datasb.append(StringUtils.leftPad(Integer.toHexString(minute.intValue()), 2, "0"));
        sum ^= minute.intValue();

        datasb.append(StringUtils.leftPad(Integer.toHexString(sum), 2, "0"));

        return datasb.toString().toUpperCase();
    }
}
